<template>
  <div class="slider"
       :class="{ 'is-vertical': field.vertical, 'el-slider--with-input': field.showInput }">
    <input-number
      v-model="firstValue"
      v-if="field.showInput && !field.range"
      class="slider__input"
      ref="input"
      :field="field"
      size="small">
    </input-number>
    <div class="slider__runway"
         :class="{ 'show-input': field.showInput, 'disabled': field.disabled }"
         :style="runwayStyle"
         @click="onSliderClick"
         ref="slider">
      <div
        class="slider__bar"
        :style="barStyle">
      </div>
      <slider-button
        :vertical="field.vertical"
        v-model="firstValue"
        ref="button1">
      </slider-button>
      <slider-button
        :vertical="field.vertical"
        v-model="secondValue"
        ref="button2"
        v-if="field.range">
      </slider-button>
    </div>
  </div>
</template>

<script type="text/babel">
  import InputNumber from '../../../../libs/dynamic-form/input-types/InputNumber.vue'
//  import InputCounter from '../../../../libs/dynamic-form/input-types/InputCounter.vue'
  import SliderButton from './SliderButton.vue'
  import { getStyle } from '../../utils/dom'
  import Emitter from '../../utils/emitter'

  export default {
    mixins: [Emitter],

    props: {
      field: {
        min: {
          type: Number
        },
        max: {
          type: Number
        },
        showInput: {
          type: Boolean
        },
        showInputControls: {
          type: Boolean
        },
        showStops: {
          type: Boolean
        },
        showTooltip: {
          type: Boolean
        },
        disabled: {
          type: Boolean
        },
        range: {
          type: Boolean
        },
        vertical: {
          type: Boolean
        },
        height: {
          type: String
        }
      },
      value: {
        type: [Number, Array],
        default: 1
      }
    },

    components: {
      InputNumber,
      SliderButton
    },

    data () {
      return {
        firstValue: null,
        secondValue: null,
        oldValue: null,
        dragging: false
      }
    },

    watch: {
      value (val, oldVal) {
        if (this.dragging ||
          Array.isArray(val) &&
          Array.isArray(oldVal) &&
          val.every((item, index) => item === oldVal[index])) {
          return
        }
        this.setValues()
      },

      dragging (val) {
        if (!val) {
          this.setValues()
        }
      },

      firstValue (val) {
        if (this.field.range) {
          this.$emit('input', [this.minValue, this.maxValue])
        } else {
          this.$emit('input', val)
        }
      },

      secondValue () {
        if (this.field.range) {
          this.$emit('input', [this.minValue, this.maxValue])
        }
      },

      min () {
        this.setValues()
      },

      max () {
        this.setValues()
      }
    },

    methods: {
      valueChanged () {
        if (this.field.range) {
          return ![this.minValue, this.maxValue]
            .every((item, index) => item === this.oldValue[index])
        } else {
          return this.value !== this.oldValue
        }
      },
      setValues () {
        const val = this.value
        if (this.field.range && Array.isArray(val)) {
          if (val[1] < this.field.min) {
            this.$emit('input', [this.field.min, this.field.min])
          } else if (val[0] > this.field.max) {
            this.$emit('input', [this.field.max, this.field.max])
          } else if (val[0] < this.field.min) {
            this.$emit('input', [this.field.min, val[1]])
          } else if (val[1] > this.field.max) {
            this.$emit('input', [val[0], this.field.max])
          } else {
            this.firstValue = val[0]
            this.secondValue = val[1]
            if (this.valueChanged()) {
              this.$emit('change', [this.minValue, this.maxValue])
              this.dispatch('ElFormItem', 'el.form.change', [this.minValue, this.maxValue])
              this.oldValue = val.slice()
            }
          }
        } else if (!this.range && typeof val === 'number' && !isNaN(val)) {
          if (val < this.field.min) {
            this.$emit('input', this.field.min)
          } else if (val > this.field.max) {
            this.$emit('input', this.field.max)
          } else {
            this.firstValue = val
            if (this.valueChanged()) {
              this.$emit('change', val)
              this.dispatch('ElFormItem', 'el.form.change', val)
              this.oldValue = val
            }
          }
        }
      },

      setPosition (percent) {
        const targetValue = this.field.min + percent * (this.field.max - this.field.min) / 100
        if (!this.field.range) {
          this.$refs.button1.setPosition(percent)
          return
        }
        let button
        if (Math.abs(this.minValue - targetValue) < Math.abs(this.maxValue - targetValue)) {
          button = this.firstValue < this.secondValue ? 'button1' : 'button2'
        } else {
          button = this.firstValue > this.secondValue ? 'button1' : 'button2'
        }
        this.$refs[button].setPosition(percent)
      },

      onSliderClick (event) {
        if (this.field.disabled || this.dragging) return
        if (this.field.vertical) {
          const sliderOffsetBottom = this.$refs.slider.getBoundingClientRect().bottom
          this.setPosition((sliderOffsetBottom - event.clientY) / this.$sliderSize * 100)
        } else {
          const sliderOffsetLeft = this.$refs.slider.getBoundingClientRect().left
          this.setPosition((event.clientX - sliderOffsetLeft) / this.$sliderSize * 100)
        }
      }
    },
    computed: {
      $sliderSize () {
        return parseInt(getStyle(this.$refs.slider, (this.field.vertical ? 'height' : 'width')), 10)
      },

      minValue () {
        return Math.min(this.firstValue, this.secondValue)
      },

      maxValue () {
        return Math.max(this.firstValue, this.secondValue)
      },

      barSize () {
        return this.field.range ? `${100 * (this.maxValue - this.minValue) / (this.field.max - this.field.min)}%` : `${100 * (this.firstValue - this.field.min) / (this.field.max - this.field.min)}%`
      },

      barStart () {
        return this.field.range
          ? `${100 * (this.minValue - this.field.min) / (this.field.max - this.field.min)}%`
          : '0%'
      },

      precision () {
        let precisions = [this.field.min, this.field.max, 1].map(item => {
          let decimal = ('' + item).split('.')[1]
          return decimal ? decimal.length : 0
        })
        return Math.max.apply(null, precisions)
      },

      runwayStyle () {
        return this.field.vertical ? { height: this.height } : {}
      },

      barStyle () {
        return this.field.vertical
          ? {
            height: this.barSize,
            bottom: this.barStart
          } : {
            width: this.barSize,
            left: this.barStart
          }
      }
    },

    mounted () {
      if (this.field.range) {
        if (Array.isArray(this.value)) {
          this.firstValue = Math.max(this.field.min, this.value[0])
          this.secondValue = Math.min(this.field.max, this.value[1])
        } else {
          this.firstValue = this.field.min
          this.secondValue = this.field.max
        }
        this.oldValue = [this.firstValue, this.secondValue]
      } else {
        if (typeof this.value !== 'number' || isNaN(this.value)) {
          this.firstValue = this.field.min
        } else {
          this.firstValue = Math.min(this.field.max, Math.max(this.field.min, this.value))
        }
        this.oldValue = this.firstValue
      }
    }
  }
</script>

<style>
 .slider__input{
   float: right;
   margin-top: 3px;
   display: inline-block;
   width: 130px;
   position: relative;
 }

  .slider{
    /*float: right;*/
    /*width: 400px;*/
    margin-right: 20px;
    padding: 30px 24px;
    overflow: hidden;
  }

 .slider.is-vertical {
   position: relative;
   padding: 20px;
 }

 .slider.is-vertical .slider__runway {
   height: 200px;
   width: 4px;
   height: 100%;
   margin: 0 16px;
 }

 .slider.is-vertical .slider__bar {
   width: 4px;
   height: auto;
   border-radius: 0 0 3px 3px;
 }

 .slider.is-vertical .slider__button-wrapper {
   top: auto;
   left: -16px;
   transform: translateY(50%);
 }

  .slider:after, .slider:before {
    display: table;
    content: "";
  }

  .slider:after {
    clear: both;
  }

  .slider__runway {
    width: 200px;
    height: 4px;
    margin: 16px 0;
    background-color: #e4e8f1;
    border-radius: 3px;
    position: relative;
    cursor: pointer;
    vertical-align: middle;
    display: inline-block;
  }

 .slider__runway.show-input {
   /*position: relative;*/
   /*right: 160px;*/
   /*top: -35px;*/
   /*margin:160px;*/
   /*width:auto;*/
 }

  .slider__bar {
    height: 4px;
    background-color: #20a0ff;
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
    position: absolute;
  }


</style>

